#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{
    //返回文件描述符fd
    //以 创建|写 方式打开
    

    umask(0);

    //int fd = open("log.txt",O_CREAT|O_WRONLY|O_TRUNC,0666);
    //int fd = open("log.txt",O_CREAT|O_WRONLY|O_APPEND,0666);
    int fd = open("log.txt",O_RDONLY);
    if(fd < 0)
    {
        perror("open");
        return 1;
    }
    
    printf("fd:%d\n",fd);

    //const char* msg = "Hello Write\n";
    //int cnt = 5;
    //while(cnt--)
    //{
    //    //写入文件
    //    write(fd,msg,strlen(msg));
    //}
    //const char* msg = "abcd\n";
    //write(fd,msg,strlen(msg));
    

    ////尝试写入二进制数据
    //int a = 666888;


    ////格式化a至buffer中
    //char buffer[128];
    //snprintf(buffer,sizeof(buffer),"%d\n",a);
    ////int cnt = 100;
    ////while(cnt--)
    //    //write(fd,buffer,strlen(buffer));
    
    char buffer[128];
    while(1)
    {
        int n = read(fd,buffer,sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;//置\0，构成缓冲区内字符串
            printf("%s",buffer);
        }
        else if(n == 0)
        {
            break;
        }
    }
    
    
    close(fd);

    return 0;
}
